import { useState } from "react";
import { DownOutlined, MinusOutlined, SearchOutlined, SyncOutlined } from "@ant-design/icons";
import { Button, DatePicker, Flex, Form, Input, InputNumber, Select } from "antd";
const { RangePicker } = DatePicker;

type ComponentProps = any;
interface SchemaData {
  name: string;
  label: string;
  type: string;
  componentProps?: ComponentProps;
}

interface SearchFormProps {
  schema: SchemaData[];
  rowSums?: number; // 一行元素个数
  defaultShowRows?: number; // 默认显示的行数
  onSearch?: (values: any) => void;
}

export default function SearchForm({ schema, rowSums = 3, defaultShowRows = 1, onSearch }: SearchFormProps) {
  const [form] = Form.useForm();
  const [isCollapsed, setIsCollapsed] = useState(true);

  // 是否需要显示展开/收起按钮
  const needCollapseButton = schema.length > defaultShowRows * rowSums;

  // 计算应该显示多少个表单项
  const visibleItemCount = isCollapsed && needCollapseButton ? defaultShowRows * rowSums : schema.length;

  // 计算按钮应该放在哪个位置
  const currentLastRowItemCount = visibleItemCount % rowSums;
  const hasSpaceInLastRow = currentLastRowItemCount !== 0;
  const buttonGridColumn = hasSpaceInLastRow ? currentLastRowItemCount + 1 : 1;
  const buttonGridRow = Math.ceil(visibleItemCount / rowSums) + (hasSpaceInLastRow ? 0 : 1);

  const handleSearch = () => {
    const values = form.getFieldsValue();
    console.log("search form", values);
    onSearch?.(values);
  };

  const handleReset = () => {
    form.resetFields();
    const values = form.getFieldsValue();
    onSearch?.(values);
  };

  const handleCollapse = () => {
    setIsCollapsed(!isCollapsed);
  };

  return (
    <Form form={form} labelCol={{ span: 6 }}>
      <div
        className="grid gap-x-4"
        style={{
          gridTemplateColumns: `repeat(${rowSums}, 1fr)`,
        }}
      >
        {/* 渲染表单项 */}
        {schema.map((item, index) => (
          <div
            key={`form-item-${item.name || index}`}
            style={{
              display: index < visibleItemCount ? "block" : isCollapsed ? "none" : "block",
            }}
          >
            {item.type === "rangeInput" ? (
              <Form.Item label={item.label}>
                <Flex align="center" className="w-full">
                  <Form.Item name={item.componentProps.start.name} className="m-0 w-full">
                    <InputNumber
                      {...item.componentProps.start}
                      suffix="K"
                      controls={false}
                      className="w-full"
                    />
                  </Form.Item>
                  <MinusOutlined />
                  <Form.Item name={item.componentProps.end.name} className="m-0 w-full">
                    <InputNumber
                      {...item.componentProps.end}
                      suffix="K"
                      controls={false}
                      className="w-full"
                    />
                  </Form.Item>
                </Flex>
              </Form.Item>
            ) : (
              <Form.Item name={item.name} label={item.label}>
                {item.type === "input" && <Input {...item.componentProps} />}
                {item.type === "select" && <Select {...item.componentProps} />}
                {item.type === "datepicker" && <DatePicker {...item.componentProps} className="w-full" />}
                {item.type === "rangePicker" && <RangePicker {...item.componentProps} className="w-full" />}
              </Form.Item>
            )}
          </div>
        ))}

        <div
          style={{
            gridColumn: hasSpaceInLastRow ? `${buttonGridColumn} / -1` : "1 / -1",
            gridRow: buttonGridRow,
          }}
        >
          <Form.Item>
            <Flex gap={10} justify="flex-end">
              <Button size="middle" type="primary" onClick={handleSearch} icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button size="middle" onClick={handleReset} icon={<SyncOutlined />}>
                重置
              </Button>
              {needCollapseButton && (
                <Button
                  size="middle"
                  type="link"
                  color="primary"
                  className="p-0 mr-1"
                  onClick={handleCollapse}
                >
                  <DownOutlined
                    style={{
                      transform: isCollapsed ? "rotate(0deg)" : "rotate(180deg)",
                      transition: "transform 0.3s ease-in-out",
                      display: "inline-block",
                    }}
                  />
                </Button>
              )}
            </Flex>
          </Form.Item>
        </div>
      </div>
    </Form>
  );
}
